import { globalConfig } from "../config/global";
import { createLogger } from "../core/utils/logging";
import { getArcPoint, keepDecimal, makeDiv } from "../core/utils/utils";
import { Vector } from "../core/utils/vector";
import { getSkillLevelTitle } from "../game/defines/skill_level_define";
import { SelectBtnGroup } from "../game/huds/select_btn_group";
import { getPresitgeTitle } from "../game/defines/presitge_define";

const logger = createLogger('editor/render')

export default {
  renderView(isMove = true, isNullSite = true){
    let mapClipDom = this.htmlElement.querySelector('.mapClip');
    
    if(this.mapClip){
      mapClipDom.classList.remove('remove');
      this.htmlElement.querySelector('#worldNameInput').value = this.mapClip.worldName;
      this.htmlElement.querySelector('#worldDescInput').value = this.mapClip.worldDesc;

      this.renderMapClip(this.mapClip);
    } else {
      this.htmlElement.querySelector('.mapSiteAttr').classList.add('remove');
      if(isNullSite){
        this.mapSite = null;
      }

      this.htmlElement.querySelector('.create-npc-page .mapSiteNpcs').innerHTML = '';
      this.htmlElement.querySelector('.create-good-page .mapSiteGoods').innerHTML = '';
      mapClipDom.classList.add('remove');
      this.renderWorld(this.mapData.world);
    }

    if(isMove){
      this.moveGrid([0, 0]);
    }
  },

  renderWorld(data){
    let mapContent = this.htmlElement.querySelector('.map-content')
    this.htmlElement.querySelector('.site').innerHTML = '世界';
    let space = globalConfig.map.worldSpace;
    let size = globalConfig.map.worldSize;
    let nexts = [];

    mapContent.innerHTML = '';

    data.map(item => {
      let dom = makeDiv(mapContent, `grid_${item.worldPos.join('')}`, ['worldSite'], `
        <h3>${item.worldName} [${item.worldPos}]</h3>
        <p>${item.worldDesc || ''}</p>
      `)

      dom.style.left = item.worldPos[0] * space.w + 'px';
      dom.style.top = item.worldPos[1] * space.h + 'px';
      dom.style.width = size.w + 'px';

      item.map.filter(item => item.attr && item.attr.goWorld).map(next => {
        nexts.push([
          item.worldPos,
          next.attr.goWorld.worldPos
        ]);
      });

      // 点击世界节点，进入区域
      this.trackClicks(dom, () => {
        this.mapClip = this.mapData.world.find(map => map.worldPos[0] == item.worldPos[0] && map.worldPos[1] == item.worldPos[1]);
        this.renderView();

        this.renderMapClipPanel();
      })
      // dom.addEventListener('click', () => {
      //   this.mapClip = this.mapData.world.find(map => map.worldPos[0] == item.worldPos[0] && map.worldPos[1] == item.worldPos[1]);
      //   this.renderView();
      // })
    })

    this.renderAllSite(data.map(item => {
      return {
        title: item.worldName,
        pos: item.worldPos
      }
    }));

    this.renderLine(nexts, space, size)
  },

  renderMapClip(data){
    let mapContent = this.htmlElement.querySelector('.map-content')
    this.htmlElement.querySelector('.site').innerHTML = `世界/${data.worldName}[${data.worldPos.join(', ')}]`;
    mapContent.innerHTML = '';
    let space = globalConfig.map.mapSpace;
    let size = globalConfig.map.mapSize;
    let nexts = [];

    data.map.forEach(item => {
      let isActive = this.mEditMode 
        ? this.activeMaps.indexOf(item.mapPos.join(',')) > -1 
        : this.mapSite == item;
      let dom = makeDiv(mapContent, `grid_${item.mapPos.join('')}`, ['mapSite', isActive ? 'active' : ''], `
        ${item.key} [${item.mapPos}]
      `)

      dom.style.left = item.mapPos[0] * space.w + 'px';
      dom.style.top = item.mapPos[1] * space.h + 'px';
      dom.style.width = size.w + 'px';
      dom.style.height = size.h + 'px';

      let next = item.attr.next;
      if(next){
        next.forEach(data => {
          nexts.push([
            item.mapPos,
            data.pos
          ]);
        });
      }

      this.trackClicks(dom, () => {
        if(this.mEditMode){
          let index = this.activeMaps.indexOf(item.mapPos.join(','));
          if(index > -1) {
            this.activeMaps.splice(index, 1);
            dom.classList.remove('active')
          } else {
            this.activeMaps.push(item.mapPos.join(','))
            dom.classList.add('active')
          }
          return;
        } else if(this.editMode){
          this.editSignal.dispatch(data, item);
          return;
        }

        [...this.htmlElement.querySelectorAll('.mapSite')].map(dom => {
          dom.classList.remove('active')
        });
        dom.classList.add('active');

        this.mapSite = item;
        this.renderMapSitePanel();
      })
    });

    this.renderAllSite(data.map.map(item => {
      return {
        title: item.key,
        pos: item.mapPos
      }
    }));
    this.renderLine(nexts, space, size)
  },

  renderMapSitePanel(){
    this.htmlElement.querySelector('.mapSiteAttr').classList.remove('remove');
    let keyInput = this.htmlElement.querySelector('#mapKeyInput');
    keyInput.innerHTML = this.mapSite.key;

    // this.htmlElement.querySelector('.mapSitePos').innerHTML = `[${this.mapSite.mapPos}]`

    this.renderMapSiteGoWorld();
    this.renderMapSiteNexts();
    this.renderMapSiteNpcs();
    this.renderMapSiteGoods();
  },

  renderMapClipPanel(){
    this.renderMapClipNpcs();
    this.renderMapClipGoods();
  },

  renderAllSite(data){
    let siteList = this.htmlElement.querySelector('.site-list')
    siteList.innerHTML = '';

    data.map(item => {
      let dom = makeDiv(siteList, ``, ['styledButton', 'success'], `
        ${item.title} [${item.pos}]
      `);

      this.trackClicks(dom, () => {
        this.moveGrid(item.pos)
      })
    })
  },
  
  renderPoint(pos){
    let mapWrapper = this.htmlElement.querySelector('.map-wrapper');
    let point = this.htmlElement.querySelector('.point')
    let space = null;

    if(this.mapClip){
      space = globalConfig.map.mapSpace;
    } else {
      space = globalConfig.map.worldSpace;
    }
    
    let mouse = new Vector(pos.x - mapWrapper.offsetLeft, pos.y - mapWrapper.offsetTop);
    mouse = mouse.sub(new Vector(this.moveX, this.moveY))

    let x = Math.floor(mouse.x / space.w);
    let y = Math.floor(mouse.y / space.h);

    point.innerHTML = `[${x}, ${y}] ${keepDecimal(this.scale, 2)}`;

    this.currentPos = [x, y];

    point.style.left = pos.x + 'px';
    point.style.top = pos.y + 'px';
  },

  renderLine(data, space, size){
    let mapLine = this.htmlElement.querySelector('.map-line');
    mapLine.innerHTML = '';

    this.lines = [];

    data.map(item => {
      if(this.isRenderLine(item)) return;

      let line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
      line.id = `line_${item[0]}_${item[1]}`;
      let start = [item[0][0] * space.w + size.w / 2 + 5000, item[0][1] * space.h + size.h / 2 + 5000];
      let end = [item[1][0] * space.w + size.w / 2 + 5000, item[1][1] * space.h + size.h / 2 + 5000];
      
      this.renderArcLine([start, end])
      // if(start[0] !== end[0] && start[1] !== end[1]){
      // } else {
      //   line.setAttribute('x1', start[0]);
      //   line.setAttribute('y1', start[1]);
      //   line.setAttribute('x2', end[0]);
      //   line.setAttribute('y2', end[1]);
      //   line.setAttribute('style', `stroke:#888;stroke-width:2`);
  
      //   mapLine.appendChild(line);
      // }
      
      this.lines.push(item);
    })

    // this.renderArrow(space, size);
  },

  renderArcLine(posArr){
    let mapLine = this.htmlElement.querySelector('.map-line');
    let path = document.createElementNS('http://www.w3.org/2000/svg', 'path');

    let AnglePos = getArcPoint(posArr[0], posArr[1], 10);
    path.setAttribute('d', `M${posArr[0].join(' ')} Q${AnglePos[0].join(' ')} ${posArr[1].join(' ')}`)
    mapLine.appendChild(path);
  },

  // TODO 斜角位置不正确，样式不好看，以后再加相关功能
  renderArrow(space, size){
    let mapArrow = this.htmlElement.querySelector('.map-arrow');
    mapArrow.innerHTML = '';

    this.lines.map(line => {
      let arrow = document.createElement('img');
      arrow.src = 'res/ui/icons/arrow_top.svg';
      arrow.classList.add('arrow');

      let start = line[0];
      let end = line[1];

      let left = start[0] * space.w + size.w / 2 - 15;
      let top = (start[1] * space.h + size.h / 2) - 15;

      let y = start[1] - end[1];
      top += (-50) * y;

      let x = start[0] - end[0];
      left += (-size.w / 2 - 10) * x;

      let rotate = 0;
      if(y != 0 && x != 0){
        if(y < 0 && x < 0) {
          rotate = 270 + 45;
        }
        if(y < 0 && x > 0) {
          rotate = 45;
        }
        if(y > 0 && x < 0) {
          rotate = 180 + 45;
        }
        if(y > 0 && x > 0) {
          rotate = 90 + 45;
        }
      } else {
        rotate = y > 0 ? 0 
          : x > 0 ? 270
          : x < 0 ? 90 : 180
      }

      arrow.style.left = left + 'px';
      arrow.style.top = top + 'px';
      arrow.style.transform = `rotate(${rotate}deg)`

      mapArrow.appendChild(arrow);
    })
  },

  renderSelectBtn(){
    this.attrPanel = new SelectBtnGroup(null, this.htmlElement, '.select-page-btn', 
      [
        {
          text: '定位',
          active: true,
          page: '.attr-panel|pos-page',
        },
        {
          text: '地板',
          page: '.attr-panel|mapSite-attr-page'
        },
        {
          text: 'Npc',
          page: '.attr-panel|npc-page'
        },
        {
          text: 'C-Npc',
          page: '.attr-panel|create-npc-page'
        },
        {
          text: 'Good',
          page: '.attr-panel|good-page',
        },
        {
          text: 'C-Good',
          page: '.attr-panel|create-good-page',
        },
      ]
    )
  }
}